import { useState, useEffect } from 'react';
import { Input, Form, Button } from 'antd';
import Dynamic from './Dynamic';

const DynamicForm = (props) => {
  // const [form] = Form.useForm();
  const [list, setList] = useState([]);
  const [id, setId] = useState(1);
  useEffect(() => {
    setList(props.defaultList); // 可接受编辑参数
    setId(props.defaultList.length + 1);
  }, []);

  const add = () => {
    let newId = id + 1;
    list.push(newId);
    setId(newId);
    setList(JSON.parse(JSON.stringify(list)));
  };
  const deleteList = (index) => {
    const newlist = list.filter((v) => v !== index);
    setList(JSON.parse(JSON.stringify(newlist)));
    let keys = props.form.getFieldsValue();
    delete keys[`params${index}`];
    props.form.setFieldsValue(keys);
  };

  return (
    <div>
      <Form autoComplete="off" form={props.form}>
        {list.length > 0 &&
          list.map((k, index) => {
            return (
              <>
                <Form.Item
                  name={`params-inner${k}`}
                  rule={[{ required: true, message: '必须填' }]}
                >
                  <Input />
                </Form.Item>
                <Form.Item
                  key={index}
                  label={`params${index + 1}`}
                  name={`params${k}`}
                >
                  <Dynamic deleteList={deleteList} k={k} />
                  {/* <Form.Item
                        name={`params-inner${k}`} 
                        rule={[{required: true, message: '必须填'}]}
                        ><Input />
                        </Form.Item>
                        <Form.Item
                        key={`params-delete${index+1}`}
                        ><Button onClick={() => deleteList(k)}>Delete</Button></Form.Item> */}
                </Form.Item>
              </>
            );
          })}
        <Button onClick={add}>Add</Button>
      </Form>
    </div>
  );
};

export default DynamicForm;
